import json

from django.db.models.query import QuerySet
from django.views import View
from rest_framework.generics import ListAPIView, RetrieveAPIView, GenericAPIView
from rest_framework.mixins import ListModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from recruit.models import Recruit
from recruit.serializers.Recruits import RecruitsNewSerializers, RecSer


class RecruitsNewView(ListAPIView):
    serializer_class = RecruitsNewSerializers
    queryset = Recruit.objects.all()

class RecruitsRecommendView(ListAPIView):
    serializer_class = RecruitsNewSerializers
    queryset = Recruit.objects.all()

class RecruitsIdView(RetrieveAPIView):
    queryset = Recruit.objects.all()
    serializer_class = RecruitsNewSerializers

class RecruitsIdVisitView(APIView):
    def put(self, request, pk):
        try:
            recs=Recruit.objects.get(pk=pk)
        except Exception as e:
            raise Response("Http404")
        visits=recs.visits
        new_vis=visits+1
        Ent_dict={'visits':new_vis}
        serializers=RecruitsNewSerializers(instance=recs,data=Ent_dict,partial=True)
        rlt=serializers.is_valid()
        if rlt:
            serializers.save()
        return Response({"message":"更新成功","success":True})
class RecruitsIdCollectView(ModelViewSet):
    queryset = Recruit.objects.all()
    serializer_class = RecruitsNewSerializers

    def post(self,request,pk):
        user=request.user
        if not user.is_authenticated:
            return Response({'message':'请先登录'})
        rec=self.get_object()
        if user in rec.users.all():
            rec.users.remove(user)
            rec.save()
            return Response({'success': True, 'message': '取消收藏'})
        else:
            rec.users.add(user)
            rec.save()
            return Response({'success': True, 'message': '收藏成功'})


class RecruitsCityView(ListModelMixin,GenericAPIView):
    serializer_class = RecruitsNewSerializers
    def post(self,request):
        json_dict=json.loads(request.body)
        name=json_dict.get('cityname')
        keyword=json_dict.get('keyword')
        queryset = Recruit.objects.filter(city=name,
                               jobname__contains=keyword)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
